import { useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { MapKitControl } from './map-kit';
import type { IMapKitControlOnAddParams, IMapKitControlOptions, ISMap } from './map-kit';

export type IMapControlProps = Pick<IMapKitControlOptions, 'position' | 'map' | 'className'> & {
  render?: ((params: { map: ISMap }) => React.ReactNode) | React.ReactNode;
};

const useMapControl = (props: IMapKitControlOptions) => {
  const { map } = props;
  const [data, setData] = useState<IMapKitControlOnAddParams>();
  useMemo(() => {
    if (map) map.addControl(new MapKitControl({ ...props, onAdd: setData }));
  }, []);

  return data;
};

export const MapControl = (props: IMapControlProps) => {
  const { map, render = null, ...restProps } = props ?? {};
  const { container } = useMapControl({ map, ...restProps }) ?? {};

  if (!container || !map || !render) return null;
  return createPortal(typeof render === 'function' ? render({ map }) : render, container);
};
